import { dictAll, serviceUrl } from "./api/system";
import { getUserInfo } from "./api/user";
import { appTokenInstance } from "./utils/appToken";
import { dataCollection } from "./utils/dataCollection";
import { loginInstance } from "./utils/login";
import { theme } from "./utils/theme/index";
import { uuidv4 } from "./utils/uuid";

interface pageProps {
  count: number; //打开次数
  enterTime: number;
  leaveTime: number;
  remainTime: number; //停留时长
}
let referrerName = "";
let referrerPhone = "";

// app.ts
App<IAppOption>({
  globalData: {
    code: "",
    anonymousCode: "",
    baseUrl: "",
    loginStatus: false, //是否登录
    currentCity: "",
    cityList: [],
    openId: "",
    sessionKey: "",
    coords: { lng: 0, lat: 0 },
    cityDrivingSchool: new Map(),
    isPC: false,
    appTokenStatus: false,
    regionMap: new Map(),
    dataCollection: {
      scene: 1000, //访问来源
      enterTime: 0, //访问时间
      leaveTime: "",
      remainTime: 0, //停留时间
      platform: "", //用户设备
      model: "",
      userInfo: {}, //用户信息
      userLocation: "", //用户位置
      city: new Map<string, number>(),
      region: new Map<string, number>(),
      class: new Map<string, number>(), //记录班别
      product: new Map<string, number>(), //记录学车类型
      site: new Map<string, number>(), //记录场地
      page: new Map<string, pageProps>(), //访问的页面{key:path,value:{list:[]}}
    },
    theme: theme,
    appBarComp: null,
    dictMap: new Map<string, any>(),
  },
  onLaunch(info: any) {
    referrerName = info.query.nickname;
    referrerPhone = info.query.phone;

    let uuid = wx.getStorageSync("uuidv4") ?? "";
    if (!uuid) {
      uuid = uuidv4();
      wx.setStorageSync("uuidv4", uuid);
    }

    console.log("theme", this.globalData.theme, "uuidv4", uuid);

    //初始化默认主题red
    wx.setStorageSync("themeCode", "red");
    const theme = this.globalData.theme.get("red");
    for (const key in theme) {
      this.globalData.dictMap.set(key, theme[key]);
    }

    const updateManager = wx.getUpdateManager();

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
    });

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: "更新提示",
        content: "新版本已经准备好，是否重启应用？",
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            wx.clearStorage();
            updateManager.applyUpdate();
          }
        },
      });
    });

    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    });

    //获取客户端信息
    wx.getSystemInfo({
      success: (res: any) => {
        console.log("getSystemInfo", res);
        this.globalData.dataCollection.model = res.model;
        this.globalData.dataCollection.platform = res.platform;

        if (res.platform === "windows" || res.platform === "mac") {
          //电脑端
          wx.setStorageSync("isPC", true);
        } else {
          wx.setStorageSync("isPC", false);
        }
      },
    });

    //小程序打开即获取客服地址
    serviceUrl().then((res) => {
      wx.setStorageSync("serviceUrl", res.result);
    });

    //获取所有小程序的字典
    // dictAll().then(res => {
    //   for (const key in res.result) {
    //     console.log(key, JSON.parse(res.result[key]))
    //     const list: any[] = JSON.parse(res.result[key])
    //     if (!this.globalData.dictMap.has(key)) {
    //       const itemMap = new Map<string, any>()
    //       list.forEach((item: any) => {
    //         itemMap.set(item.text, isJSON(item.value) ? JSON.parse(item.value) : item.value)
    //       })
    //       this.globalData.dictMap.set(key, itemMap)
    //     }
    //   }
    //   console.log('dictMap', this.globalData.dictMap)
    // })

    //数据采集 访问来源场景
    this.globalData.dataCollection.scene = info.scene;
  },
  onHide() {
    this.globalData.dataCollection.leaveTime = new Date().getTime();

    loginInstance.updateCule();

    loginInstance.JudgmentExpirationInstance.clear();

    appTokenInstance.JudgmentExpirationInstance.clear();
  },
  onShow() {
    dataCollection.reset(this.globalData.dataCollection);

    loginInstance.JudgmentExpirationInstance.clear();
    loginInstance.init();

    appTokenInstance.JudgmentExpirationInstance.clear();
    //获取用户信息
    if (wx.getStorageSync("accessToken")) {
      getUserInfo();
    }

    this.globalData.dataCollection.enterTime = new Date().getTime();

    console.log("dataCollection", this.globalData.dataCollection);
  },
});
